<%@ taglib uri="/tags/struts-bean" prefix="bean"%>
<%@ taglib uri="/tags/struts-html" prefix="html"%>
<%@ taglib uri="/tags/struts-logic" prefix="logic"%>
<%@ taglib uri="/tags/core" prefix="c"%>		
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:setBundle basename="messages"/>
<script type="text/javascript" src="js/utils.js"></script>


<script>
	var emptyForecastList = false;
	<logic:notEmpty name="InstructionPurchaseDetailForm" property="ipdView.customerView.customerId">
		<logic:empty name="InstructionPurchaseDetailForm" property="ipdView.instructionsForecastsDetailView.details">	
			emptyForecastList = true;
		</logic:empty>
	</logic:notEmpty>
	
	var conUnit = <bean:write name="CON_UNIT"/>;
	var tonsUnit = 1/conUnit;
	var futuresUnit = 1;
	function submitSearchCustomer(){
		var form1 = document.getElementById("searchCustomerForm");
		var customerId = document.getElementById("ipdView.customerId");
		form1.customerId.value = customerId.value;
		form1.submit();
	}
	
	function submitSearchProduct(){
		var form = document.getElementById("searchProductForm");
		var customerId = document.getElementById("ipdView.customerId");
		if(customerId.value==undefined || customerId.value==''){
		    alert('<bean:message key="label.purchases.instructions.detail.customerempty"/>');
		}else{
			form.customerId.value = customerId.value;
	        form.submit();
		}
	}
	
	function validate(forma){
		var retVal = false;
		var customerId = document.getElementById("ipdView.customerId").value;	
		var futureTypeId = document.getElementById("ipdView.futureTypeId").value;		
		var strategyId = document.getElementById("ipdView.instructionStrategyId").value;
		var strategyTypeId= document.getElementById("ipdView.instructionTypeId").value;
		var status = document.getElementById("ipdView.status").value;
		var futures = forma.futuresQuantity;
		var montSug = forma.montSugQuantity;
		var stopLoss = forma.stopLossQuantity;
		var futuresLength = futures.length;
		var forecastContractedSelected = document.getElementById("itemQuantity").value;
		var errorsLen = "";
		
		var tons = forma.tons.value.replace(/,/g, "");
		var cornQuantity = forma.cornQuantity.value.replace(/,/g, "");

		if( cornQuantity == '' ){
			cornQuantity = '0';
		}
		
		futuresUnit = (parseFloat(conUnit)*parseFloat(cornQuantity))+.99;

		
		if(parseFloat(tons) > (parseFloat(cornQuantity)+parseFloat(tonsUnit))){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.wrongfuturesnumber"/>';
			errorsLen = errorsLen + ' : <'+parseInt(futuresUnit) +'>\n';
		}
		

		if(customerId == ""){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.customerempty"/>\n';
		}

		if(futureTypeId == "-1"){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.typeempty"/>\n';
		}
		if(strategyId == "-1"){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.purchaseestratetyempty"/>\n';			
		}
		if(strategyTypeId == "-1"){
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.purchaseestratetytypeempty"/>\n';
		}
		
		for( var index = 0; index < futuresLength; index++ ){
			
			
			if( trim(futures[index].value) != ''  || trim(montSug[index].value) != ''  ){
			
				if( trim(futures[index].value) == '' || ( trim(montSug[index].value) == '' && strategyId != "1" )){
			
					errorsLen = errorsLen + '\t<bean:message key="label.purchases.instructions.line"/> '+(index+1)+' :\n';
					if( trim(futures[index].value) == '' ){			
						errorsLen = errorsLen +  '\t\t<bean:message key="error.purchases.instructions.future.requiered"/>\n';
					}
					if( trim(montSug[index].value) == '' ){
						if( strategyId != "1" ){
							errorsLen = errorsLen +  '\t\t<bean:message key="error.purchases.instructions.sug.amount"/>\n';
						}
					}else{
						if( parseFloat( montSug[index].value.replace(/,/g, "") ) > parseFloat( stopLoss[index].value.replace(/,/g, "") ) ){
							errorsLen = errorsLen +  '\t\t<bean:message key="error.purchases.instructions.sug.amount.minus.to.stop.loss"/>\n';
						}
					}
				}else{
					if( trim(montSug[index].value) != '' ){
						if( parseFloat( montSug[index].value.replace(/,/g, "") ) > parseFloat( stopLoss[index].value.replace(/,/g, "") ) ){
							errorsLen = errorsLen +  '\t<bean:message key="label.purchases.instructions.line"/> '+(index+1)+' :\n\t\t<bean:message key="error.purchases.instructions.sug.amount.minus.to.stop.loss"/>\n';
						}
					}
				}
			}
		}
		
		if(forecastContractedSelected==""){		
			errorsLen = errorsLen + ' - <bean:message key="label.purchases.instructions.detail.commitmentlist.empty"/>\n';
		}
		
		if(errorsLen == ""){
			retVal = true;
		}else{
			errorsLen = '<bean:message key="label.common.errors"/>: \n' + errorsLen;
			alert(errorsLen);
		}
		return retVal;
	}
	
	function sumFutures(forma){
		var futures = forma.futures;
   		var tons = forma.tons;
		var futureQuantity = forma.futuresQuantity;
		var futuresSum = 0;
		for (i = 0; i < futureQuantity.length; i++){
			if( trim(futureQuantity[i].value) != "" ){
				futuresSum = futuresSum + parseFloat(futureQuantity[i].value.replace(/,/g, ""));
			}
		}
		futures.value = addCommas(futuresSum);
		tons.value = addCommas(decimales( futuresSum/conUnit,2 ));
	}
	
	function sumQuantity(forma){
   		var quantityItem = forma.itemQuantity;
   		var quantityCornItem = forma.cornQuantity;
   		var futuresReqTotal = forma.futuresReqTotal;
   		
   		var quantity = 0;
   		var quantityCorn = 0;
   		var futuresReq = 0;
   		
   		var checks = forma.instructionForecastCheck;
   		var inc = forma.quantity;
   		var inc2 = forma.quantityCorn;
   		var inc3 = forma.futuresReq;
   		
   		for (i = 0; i < checks.length; i++){
      		if (checks[i].checked){      		
        		quantity = quantity + parseFloat(inc[i].value.replace(/,/g, ""));
        		quantityCorn = quantityCorn + parseFloat(inc2[i].value.replace(/,/g, ""));
        		futuresReq = futuresReq + parseFloat(inc3[i].value.replace(/,/g, ""));
      		}
		}
		
		quantityItem.value = addCommas( decimales( quantity, 2 ) );
		quantityCornItem.value = addCommas( decimales( quantityCorn, 2 ) );
		futuresReqTotal.value = addCommas(parseInt(futuresReq+.99));
	}
	
		function cleanValues(row){   			  			
			if(document.InstructionPurchaseDetailForm.futuresQuantity.length != undefined){
				document.InstructionPurchaseDetailForm.futuresQuantity[row].value = "";
				document.InstructionPurchaseDetailForm.montSugQuantity[row].value = "";
				document.InstructionPurchaseDetailForm.stopLossQuantity[row].value = "";
				document.InstructionPurchaseDetailForm.accountFuturePeriodId[row].selectedIndex = 0;
				document.InstructionPurchaseDetailForm.applicationFuturePeriodId[row].selectedIndex = 0;
				document.InstructionPurchaseDetailForm.minorPriceSelect[row].selectedIndex = 0;
				sumFutures(document.InstructionPurchaseDetailForm);
			}
		}
		
		function sendRequest(url, form, field, fieldDescription, maxlength){
			var customerDescription = "";
			//if( trim( field.value ).length == maxlength ){
				form.id.value = trim( field.value );
				retrieveURL(url, form.name);
			//}else{
//				fieldDescription.value = "";
			//}
		}
</script>
<html:form action="/searchCustomerPurchaseInstruction">
	<input type="hidden" value="" name="id"/>
</html:form>
<html:form action="/searchProductPurchaseInstruction">
	<input type="hidden" value="" name="id"/>
</html:form>
<html:form action="/addInstructionPurchaseDetail" styleId="mainForm" onsubmit="return validate(this);">
	<input type="hidden" name="present" value="1"/>
	<table width="99%" align="center" border="0">
		<tr>
			<td colspan="2">
			<table width="100%" align="right" cellpadding="2" cellspacing="1"
				border="0" bgcolor="#CCCCC0">
				<tr>
					<td align="left" class="titulocolumna"><bean:message
						key="label.purchases.instructions.edit.commitment.purchase" /></td>
				</tr>
			</table>
			</td>
		</tr>
		<tr>
			<td colspan="2" align="center">
			<table align="center" width="100%" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">

				<tr>
					<td class="titulocolumna" align="center" width="30%">
						<bean:message key="label.purchases.instructions.detail.customerdes" />
					</td>
					<td class="titulocolumna" align="center" width="30%">
						<bean:message key="label.purchases.instructions.detail.productdes" />
					</td>

					<td class="titulocolumna" align="center" width="9%"><bean:message
						key="label.purchaseinstructiondetail.type" /></td>

					<td class="titulocolumna" align="center" width="9%"><bean:message
						key="label.purchaseinstructiondetail.purchase.strategy" /></td>

					<td class="titulocolumna" align="center" width="14%"><bean:message
						key="label.purchaseinstructiondetail.type.strategy" /></td>

					<td class="titulocolumna" align="center" width="8%"><bean:message
						key="label.purchaseinstructiondetail.status" /></td>
				</tr>

				<tr class="columnadatoPar">
					<td align="left">
						<html:text size="3" maxlength="6" property="ipdView.customerView.customerId" styleId="ipdView.customerId" styleClass="campo_texto" onkeydown="return (numeric(event, 0) && noPaste(event, this));" onkeyup="extractNumber(this,2,false);" onfocus="this.select();"  onchange="sendRequest('searchCustomerPurchaseInstruction.do?x=1', document.SearchCustomerPurchaseInstructionForm, this, this.form.customerDescriptionForm, 6);"/> 
						- 
						<span id="customerDescriptionAjax">
						    <html:text readonly="true" size="32"  styleId="customerDescriptionForm" property="ipdView.customerView.description"  styleClass="campo_texto"/>
					    </span> 
					    <html:button styleClass="boton_short" property="backButton" onclick="submitSearchCustomer();">...</html:button>
					</td>
					<td align="center">
						 <span id="materialDescriptionAjax">
						     <c:out value="${nSelectedProducts}" /> <fmt:message key="label.purchaseinstructiondetail.product.selected"/>
						 </span>
						 <html:button styleClass="boton_short" property="backButton" onclick="submitSearchProduct();">...</html:button>
					</td>
					<td class="etiqueta_campo" style="text-align: center;"><html:select
						property="ipdView.futureTypeId"
						styleId="ipdView.futureTypeId"
						styleClass="campo_texto" >
						<html:option value="-1">
							<bean:message key="label.common.select" />
						</html:option>
						<html:option value="D">
							<bean:message key="label.futuretype.D" />
						</html:option>
						<html:option value="F">
							<bean:message key="label.futuretype.F" />
						</html:option>
					</html:select></td>

					<td class="etiqueta_campo" style="text-align: center;"><html:select
						property="ipdView.instructionStrategyId"
						styleId="ipdView.instructionStrategyId"
						styleClass="campo_texto" >
						<html:option value="-1">
							<bean:message key="label.common.select" />
						</html:option>
						<html:option value="1">
							<bean:message key="label.strategyid.1" />
						</html:option>
						<html:option value="2">
							<bean:message key="label.strategyid.2" />
						</html:option>
						<html:option value="3">
							<bean:message key="label.strategyid.3" />
						</html:option>
						<html:option value="4">
							<bean:message key="label.strategyid.4" />
						</html:option>
					</html:select></td>

					<td class="etiqueta_campo" style="text-align: center;"><html:select
						property="ipdView.instructionTypeId"
						styleId="ipdView.instructionTypeId"
						styleClass="campo_texto" >
						<html:option value="-1">
							<bean:message key="label.common.select" />
						</html:option>
						<html:option value="1">
							<bean:message key="label.strategytypeid.1" />
						</html:option>
						<html:option value="2">
							<bean:message key="label.strategytypeid.2" />
						</html:option>
						<html:option value="3">
							<bean:message key="label.strategytypeid.3" />
						</html:option>
						<html:option value="4">
							<bean:message key="label.strategytypeid.4" />
						</html:option>
					</html:select></td>

					<td class="etiqueta_campo" style="text-align: center;"><html:select
						property="ipdView.status"
						styleId="ipdView.status"
						styleClass="campo_texto" >
						<html:option value="1">
							<bean:message key="label.purchaseinstructiondetail.status.1" />
						</html:option>
					</html:select>
					</td>
				</tr>
				</table>
			 </td>
			</tr>
				<!-- Forecast tabla izquierda  -->
			<tr>
			<td width="40%" align="right" valign="top">
				<span id="periodForecast">
					<table width="95%" align="right" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
						<tr>
							<td colspan="7" align="center" class="titulocolumna">
								<bean:message key="label.purchases.instructions.edit.commitment.purchase.detail"/>
							</td>
						</tr>
						<tr class="columnadatoPar">
							<td align="right" colspan="2">
								<bean:message key="label.instructionsforecast.totals"/>
							</td>
							<td align="right">
								<html:text styleId="itemQuantity" property="ipdView.itemQuantity" readonly="true" size="8" styleClass="campo_texto_r" />
							</td>
							<td align="right">
								<html:text styleId="cornQuantity" property="ipdView.cornQuantity" readonly="true" size="8" styleClass="campo_texto_r" />
							</td>
							<td align="left" colspan="3">
								<input type="text" name="futuresReqTotal" id="futuresReqTotal" readonly="readonly" size="2" class="campo_texto_r"/>
							</td>
						</tr>
						<tr>
							<td class="titulocolumna" align="center" width="4%">&nbsp;</td>
							<td class="titulocolumna" align="center" width="16%">
								<bean:message key="label.instructionsforecast.period"/>
							</td>	
							<td class="titulocolumna" align="center" width="17%">
								<bean:message key="label.instructionsforecast.quantity"/>
							</td>	
							<td class="titulocolumna" align="center" width="20%">
								<bean:message key="label.instructionsforecast.quantity.corn"/>
							</td>	
							<td class="titulocolumna" align="center" colspan="2">
								<bean:message key="label.instructionsforecast.futures"/>
							</td>	
							<td class="titulocolumna" align="center" width="17%">
								<bean:message key="label.instructionsforecast.current"/>
							</td>
						</tr>
						<c:forEach items="${InstructionPurchaseDetailForm.ipdView.instructionsForecastsDetailView.details}" var="detail" varStatus="loop">
							<input type="hidden" id='quantity' name='quantity'  value='<c:out value="${detail.contracted}" />'/>
							<input type="hidden" id='quantityCorn' name='quantityCorn'  value='<c:out value="${detail.cornContracted}" />'/>
							<input type="hidden" id='futuresReq' name='futuresReq'  value='<c:out value="${detail.futures}" />'/>
							<tr <c:if test="${(loop.index%2)==0}"> class="columnadatoPar"</c:if> <c:if test="${(loop.index%2)!=0}">class="columnadatoNon"</c:if>>
								<td>
									<input type='checkbox' onclick="sumQuantity(this.form);"  id="instructionForecastCheck" name='ipdView.instructionsForecastsDetailView.checked'  <c:if test="${detail.forecastAdded==1}" >checked</c:if> value='<c:out value="${loop.index}"/>' />
								</td>
								<td align="center">
									<a href="showForecastByPeriod.do?month=<c:out value="${detail.month}" />&year=<c:out value="${detail.year}" />&customerId=<c:out value="${detail.customerId}" />&instructionPurchaseDetailId=-1">
										<c:out value="${detail.year}" />.<fmt:formatNumber maxIntegerDigits="2" minIntegerDigits="2" pattern="##" value="${detail.month}"></fmt:formatNumber>
									</a>
								</td>
								<td  align="right">
									<c:out value="${detail.contracted}" />
								</td>
								<td  align="right">
									<c:out value="${detail.cornContracted}" />
								</td>
								<td width="10%" align="right">
									<c:out value="${detail.futuresFloored}" />
								</td>
								<td width="14%"  align="right">
									(<c:out value="${detail.futures}" />)
								</td>
								<td  align="right">
									<c:if test="${detail.forecastAdded==1}" ><c:out value="${detail.actual}" /></c:if>
								</td>
							</tr>
							</c:forEach>
						</table>
					</span>
			</td>
			<td width="60%" align="left" valign="top">
			<!-- FUTURES TABLA DERECHA -->
				<table width="450px" align="left" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
					<tr>
						<td colspan="7" align="center" class="titulocolumna">
							<bean:message key="label.purchases.instructions.label"/>
						</td>
					</tr>
					<tr class="columnadatoPar">
						<td align="center" >
							<html:text styleId="futures" property="ipdView.futures" readonly="true" size="3" styleClass="campo_texto_r" />
							<html:hidden styleId="tons" property="ipdView.tons" />
						</td>
						<td colspan="6" align="left"><bean:message key="label.instructionsforecast.totals"/></td>
					</tr>
					<tr>
						<td class="titulocolumna">
							<bean:message key="menu.module.corn.sub.future"/>
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.price"/>												
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.furchase.period"/>
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.furchase.application"/>												
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.minor.price"/>												
						</td>
						<td class="titulocolumna">
							<bean:message key="label.purchases.instructions.futures.stoploss"/>								
						</td>
						<td class="titulocolumna">
							&nbsp;
						</td>
					</tr>
					<logic:notEmpty name="InstructionPurchaseDetailForm" property="ipdView.instructionsFuturesView">
						<c:forEach items="${InstructionPurchaseDetailForm.ipdView.instructionsFuturesView}" var="row" varStatus="loop">
							<tr <c:if test="${(loop.index%2)==0}">class="columnadatoPar" </c:if><c:if test="${(loop.index%2)!=0}">class="columnadatoNon"</c:if>>
								<td align="center">
								<html:hidden name="row" property="purchaseInstructionFutureId"/>
								<html:hidden name="row" property="purchaseInstructionDetailId"/>
									<input type="hidden" style="text-align: right;" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].purchaseInstructionDetailId' value='<c:out value="${row.purchaseInstructionDetailId}"/>' />
									<input id="futuresQuantity" type="text" style="text-align: right;" onblur="sumFutures(this.form)"  id="futuresQuantity" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].quantity' value='<logic:notEqual name="row" property="quantity" value="0"><c:out value="${row.quantity}"/></logic:notEqual>' class="campo_texto" onfocus="this.select();" onkeydown="return (numeric(event, 0) && noPaste(event, this));" onkeyup="extractNumber(this,2,false);" size="3">
								</td>
								<td align="center">						
									<input id="montSugQuantity" type="text" style="text-align: right;" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].price' onfocus="this.select();" value='<c:out value="${row.price}"/>' class="campo_texto" onfocus="this.select();" onkeydown="return (numeric(event, 1) && noPaste(event, this));" onkeyup="extractNumber(this,4,false);" size="5">
								</td>
								<td align="center">
									<select id="accountFuturePeriodId" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].accountFuturePeriodId' class="campo_texto" >
										<c:forEach var="row" items="${InstructionPurchaseDetailForm.ipdView.instructionsFuturesView[loop.index].accountPeriod}">	
											<option	
												value='<c:out value="${row.periodId}" />'
												<c:if test="${row.selected}" >selected</c:if> >
												<c:out value="${row.periodName}" /> 
											</option>
										</c:forEach>
									</select>													
								</td>
								<td align="center">	
									<select id="applicationFuturePeriodId" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].applicationFuturePeriodId' class="campo_texto" >							
										<c:forEach var="row" items="${InstructionPurchaseDetailForm.ipdView.instructionsFuturesView[loop.index].applicationPeriod}">
											<option	
												value='<c:out value="${row.periodId}" />'
												<c:if test="${row.selected}" >selected</c:if> >
												<c:out value="${row.periodName}" /> 
											</option>								
										</c:forEach>
									</select>										
								</td>
								<td align="center">
								  <select id="minorPriceSelect" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].miniorPrice' class="campo_texto" >
								  	<option value="Y" ><bean:message key="label.common.yes" /></option>
								  	<option value="N" ><bean:message key="label.common.no" /></option>
								  </select>					  					  
								</td>
								<td align="center">						
									<input id="stopLossQuantity" type="text" name='ipdView.instructionsFuturesView[<c:out value="${loop.index}"/>].stopLoss' onfocus="this.select();" value='<c:out value="${row.stopLoss}"/>' style="text-align: right;" onkeydown="return (numeric(event, 1) && noPaste(event, this));" onkeyup="extractNumber(this,4,false);" class="columnanumero" size="5" />
								</td>
								<td>
									<a href="#" onclick='cleanValues("<c:out value="${loop.index}"/>")'>
										<img alt="<bean:message key="login.button.clear" />" src="images/erase.png" border="0">
									</a>
								</td>
							</tr>	
						</c:forEach>
					</logic:notEmpty>
				</table>
			<!-- FUTURES TABLA DERECHA-->
		</td>
	</tr>
</table>
<!-- PARTE BAJA -->
<br/>
		<table align="center" width="99%" cellpadding="2" cellspacing="1" border="0" bgcolor="#CCCCC0">
			<tr>
				<td colspan="10" align="center" class="columnadatoPar"><html:submit
					styleClass="boton" property="mainForm">
					<bean:message key="label.common.save" />
				</html:submit> <html:button styleClass="boton" property="backButton"
					onclick="location.href = 'goInstructionPurchaseHeader.do'">
					<bean:message key="label.common.cancel" />
				</html:button></td>
			</tr>
		</table>
</html:form>
<html:form action="/ipdSearchCustomer" styleId="searchCustomerForm">
	<input  type="hidden"" name="customerId"/>
</html:form>
<html:form action="/ipdSearchProduct" styleId="searchProductForm">
	<input  type="hidden"" name="customerId"/>
</html:form>